<!-- 用户管理 -->
<template>
  <div class="app-container">
	
	<div class="app-layout">
		<div class="left">
			<DbapiGroupTree v-model="queryParams.groupId" @node-click="handleQuery" />
		</div>
		<div class="right">
			<div class="pane">
				<div class="head">
					<span>接口列表</span>
				</div>
				<div class="body">
					<div class="table-tool-bar">
						<div style="width: 400px;">
							<el-button
							  v-hasPerm="['sys:user:add']"
							  type="primary"
							  icon="plus"
							  @click="handleOpenDialog()"
							>
							  新增
							</el-button>
							<el-button
							  v-hasPerm="'sys:user:delete'"
							  type="danger"
							  icon="delete"
							  :disabled="selectIds.length === 0"
							  @click="handleDelete()"
							>
							  删除
							</el-button>
						</div>
						<div>
							    <el-input
							      v-model="queryParams.keywords"
							      style="width:320px"
							      placeholder="输入接口名称或标识进行搜索"
							      class="input-with-select"
							    >
							      <template #append>
							        <el-button icon="search"  @click="handleQuery" />
							      </template>
							    </el-input>
						</div>
					</div>
					
					<div>
						<el-table v-loading="loading" border :data="pageData" height="calc(100vh - 260px)" @selection-change="handleSelectionChange">
						  <el-table-column type="selection" width="50" align="center" />
						  <el-table-column label="名称" width="250" align="left" prop="name" />
						  <el-table-column label="请求地址" align="left" prop="uri" />
						  <el-table-column label="开启校验" align="left" prop="status" width="160">
						    <template #default="scope">
						      <el-tag :type="scope.row.isToken == '1' ? 'success' : 'info'">
						        {{ scope.row.isToken == '1' ? "验证Token" : "不验证Token" }}
						      </el-tag>
						    </template>
						  </el-table-column>
						  <el-table-column label="创建时间" align="left" prop="createTime" width="220" />
						  <el-table-column label="操作" fixed="right" width="300">
						    <template #default="scope">
							  <el-button
							    v-hasPerm="'biz:dbapi:api:edit'"
							    type="primary"
							    icon="Tools"
							    link
							    size="small"
							    @click="sqlDrawerRef.openDialog(scope.row)"
							  >
								设置SQL
							  </el-button>
							  
						      <el-button
						        v-hasPerm="'biz:dbapi:api:edit'"
						        type="primary"
						        icon="edit"
						        link
						        size="small"
						        @click="handleOpenDialog(scope.row)"
						      >
						        编辑
						      </el-button>
							  
							  <el-button
							    v-hasPerm="'biz:dbapi:api:test'"
							    type="primary"
							    icon="Switch"
							    size="small"
							    link
							    @click="debugDrawerRef.openDialog(scope.row)"
							  >
							    调试
							  </el-button>
							  
						      <el-button
						        v-hasPerm="'biz:dbapi:api:delete'"
						        type="danger"
						        icon="delete"
						        link
						        size="small"
						        @click="handleDelete(scope.row.id)"
						      >
						        删除
						      </el-button>
						    </template>
						  </el-table-column>
						</el-table>
						
						<div style="display: flex;justify-content: flex-end;align-items: center">
							<pagination
							  v-model:total="total"
							  v-model:page="queryParams.cur"
							  v-model:limit="queryParams.limit"
							  @pagination="handleQuery"
							/>
						</div>
						
					</div>
				</div>
			</div>
		</div>
	</div>  
	  
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      @close="handleCloseDialog"
	  :close-on-click-modal="false"
    >
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="80px">

        <el-form-item label="接口名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入接口名称" />
        </el-form-item>

        <el-form-item label="所属分组" prop="groupId">
          <el-tree-select
            v-model="formData.groupId"
            placeholder="请选择所属分组"
            :data="groupOptions"
            filterable
            check-strictly
            :render-after-expand="false"
			:props="defaultProps"
          />
        </el-form-item> 


        <el-form-item label="接口标识" prop="code">
          <el-input v-model="formData.code" placeholder="请输入接口标识"  />
        </el-form-item>

        <el-form-item label="请求地址" prop="uri">
          <el-input v-model="formData.uri" placeholder="请输入请求地址" />
        </el-form-item>

        <el-form-item label="开启校验" prop="isToken">
          <el-switch
            v-model="formData.isToken"
            inline-prompt
            active-text="开启"
            inactive-text="关闭"
            :active-value="'1'"
            :inactive-value="'0'"
          />
        </el-form-item>
		
		<el-form-item label="接口排序" prop="sort">
		  <el-input-number
		    v-model="formData.sort"
		    style="width: 100px"
		    controls-position="right"
		    :min="0"
		  />
		</el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit"  :loading="loading">确 定</el-button>
          <el-button @click="handleCloseDialog" :loading="loading">取 消</el-button>
        </div>
      </template>
    </el-drawer>
	<SqlDrawer  ref="sqlDrawerRef"></SqlDrawer>
	<DebugDrawer  ref="debugDrawerRef"></DebugDrawer>
  </div>
</template>

<script setup lang="ts">
	
import DbapiAPI, { ApiForm, ApiPageVO } from "@/api/biz/dbapi";
import DbapiGroupTree from "./components/DbapiGroupTree.vue";
import DebugDrawer from "./components/DebugDrawer.vue";
import SqlDrawer from "./components/SqlDrawer.vue";

import {
  recurOptions
} from "@/utils/TreeUtil";
defineOptions({
  name: "User",
  inheritAttrs: false,
});

const sqlDrawerRef=ref();
const debugDrawerRef=ref();


const userFormRef = ref(ElForm);
const defaultProps = {
  children: 'children',
  label: 'name',
  value:'id'
}
const queryParams = reactive<any>({
  cur: 1,
  limit: 10,
});

const pageData = ref<ApiPageVO[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});

const formData = reactive<ApiForm>({
	id: "",
	groupId: "",
	name: "",
	code: "",
	uri: "",
	isToken: "",
	sort: 0
});

const rules = reactive({
  name: [{ required: true, message: "接口名称不能为空", trigger: "blur" }],
  groupId: [{ required: true, message: "接口分组不能为空", trigger: "blur" }],
  code: [{ required: true, message: "接口标识不能为空", trigger: "blur" }],
  uri: [{ required: true, message: "请求地址不能为空", trigger: "blur" }],
  isToken: [{ required: true, message: "Token校验不能为空", trigger: "blur" }],
});

// 选中的用户ID
const selectIds = ref<string[]>([]);
const groupOptions = ref<any[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
function handleQuery() {
  loading.value = true;
  DbapiAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.totalRow;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryParams.cur = 1;
  queryParams.groupId = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(row?: any) {
  dialog.visible = true;
  groupOptions.value = recurOptions(await DbapiAPI.getGroups({}),'-1');
  if (row) {
    dialog.title = "修改Api";
    Object.assign(formData, { ...row });
  } else {
    dialog.title = "新增Api";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = "";
  formData.groupId="";
  formData.name="";
  formData.code="";
  formData.isToken="0";
  formData.sort=0;
  formData.uri="";
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        DbapiAPI.save({
			id:formData.id,
			groupId:formData.groupId,
			name:formData.name,
			code:formData.code,
			uri:formData.uri,
			isToken:formData.isToken,
			sort:formData.sort,
		})
          .then(() => {
            ElMessage.success("修改Api成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        DbapiAPI.save({
			id:formData.id,
			groupId:formData.groupId,
			name:formData.name,
			code:formData.code,
			uri:formData.uri,
			isToken:formData.isToken,
			sort:formData.sort,
		})
          .then(() => {
            ElMessage.success("新增Api成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除Api?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      DbapiAPI.deleteByIds(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
	.left{
		width: 280px;
		margin-right: 10px;
	}
	.right{
		width: calc(100% - 280px);
	}
	.table-tool-bar{
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 5px;
	}
	:deep(.el-table th.el-table__cell) {
		background-color: #fafafa;
		background-image: url();
		background-image: -webkit-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -moz-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: -o-linear-gradient(top, #f2f2f2 0, #fafafa 100%);
		background-image: linear-gradient(to bottom, #f2f2f2 0, #fafafa 100%);
	}
	.well-pane{
		-webkit-border-radius: 2px;
		-webkit-background-clip: padding-box;
		-moz-border-radius: 2px;
		-moz-background-clip: padding;
		border-radius: 2px;
		background-clip: padding-box;
		-webkit-box-shadow: 0 0 3px rgba(0, 0, 0, .2);
		-moz-box-shadow: 0 0 3px rgba(0, 0, 0, .2);
		box-shadow: 0 0 3px rgba(0, 0, 0, .2);
		background-color: #fbfbfb;
		border: 0;
		color: var(--el-text-color-regular);
		margin-bottom: 30px;
		min-height: 0;
		.head{
			padding: 10px;
			text-align: left;
			border-radius: 2px 2px 0 0;
			border-bottom: 1px solid #e5e5e5;
			font-size: 16px;
		}
		
		.body{
			padding: 10px;
			color: var(--el-text-color-regular);
			font-size: 14px;
			padding-top: 0px;
			padding-bottom: 5px;
			.row{
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 8px;
				line-height: 1.42857143;
				vertical-align: top;
				border-top: 1px solid #ddd;
			}
		}
	}
</style>

